package com.aliang.shopping.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.config.OssConfig;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.mapper.GoodsSpecMapper;
import com.aliang.shopping.mapper.OrdersItemMapper;
import com.aliang.shopping.model.converter.GoodsConverter;
import com.aliang.shopping.model.po.GoodsSpec;
import com.aliang.shopping.model.po.OrdersItem;
import com.aliang.shopping.model.vo.address.AddressVO;
import com.aliang.shopping.model.vo.cart.CartShowVO;
import com.aliang.shopping.model.vo.cart.CartVO;
import com.aliang.shopping.model.vo.orders.OrdersFrontVO;
import com.aliang.shopping.service.OrdersItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ShiBaLover
 * @description 针对表【orders_item(订单列表表)】的数据库操作Service实现
 * @createDate 2025-01-04 22:07:38
 */
@Service
@AllArgsConstructor
public class OrdersItemServiceImpl extends ServiceImpl<OrdersItemMapper, OrdersItem>
        implements OrdersItemService {

    private final OssConfig ossConfig;
    private final GoodsConverter goodsConverter;
    private final GoodsSpecMapper goodsSpecMapper;

    @Override
    public List<CartShowVO> getOrdersItemInfoByPayNo(Long payNo) {
        List<CartShowVO> cartShowVO = this.baseMapper.getOrdersItemInfo(payNo);
        if (cartShowVO.isEmpty())
            // 数据为空，返回空数组
            return Collections.emptyList();
        // 获取规格信息
        List<List<CartVO>> cartVolist = cartShowVO.stream().map(CartShowVO::getCartInfo).collect(Collectors.toList());
        // 获取规格信息
        Map<Long, String> specMap = getSpecList(cartVolist);
        // 设置商品图片及规格名字
        cartShowVO.forEach(showVo -> {
            // 设置图片完整路径
            if (StrUtil.isNotBlank(showVo.getAvatar())) {
                showVo.setAvatar(ossConfig.getUrl() + showVo.getAvatar());
            }
            handleCartDataVo(specMap, showVo.getCartInfo());
        });
        return cartShowVO;
    }

    /**
     * 处理购物车数据
     *
     * @param specMap
     * @param cartVOList
     */
    private void handleCartDataVo(Map<Long, String> specMap, List<CartVO> cartVOList) {
        cartVOList.forEach(cartVO -> {
            if (StrUtil.isNotBlank(cartVO.getGoodsImage())) {
                // 获取图片第一张
                String oneMainImages = goodsConverter.getOneMainImages(cartVO.getGoodsImage());
                if (StrUtil.isNotBlank(oneMainImages))
                    //设置完成路径
                    cartVO.setGoodsImage(ossConfig.getUrl() + oneMainImages);
            }
            String goodsSpecName = cartVO.getGoodsSpecName();
            List<Long> list = JSONUtil.toList(goodsSpecName, Long.class);
            // 拼接规格名称
            List<String> collect = list.stream().map(specMap::get).collect(Collectors.toList());
            String join = CollectionUtil.join(collect, ",");
            cartVO.setGoodsSpecName(join);
            //计算折扣价
            cartVO.setGoodsScopePrice(cartVO.getGoodsPrice().multiply(cartVO.getGoodsScope())
                    //设置2位小数
                    .setScale(2, RoundingMode.HALF_UP));

        });
    }


    /**
     * 获取规格信息
     *
     * @param voList
     * @return
     */
    private Map<Long, String> getSpecList(List<List<CartVO>> voList) {
        //获取规格Id
        Set<Long> specList = new HashSet<>();
        voList.forEach(cartVO -> {
            cartVO.forEach(cart -> {
                List<Long> list = JSONUtil.toList(cart.getGoodsSpecName(), Long.class);
                specList.addAll(list);
            });
        });
        if (specList.isEmpty()) throw new DataException(ResultCodeEnum.SPEC_IS_NOT_EXIT);
        // 查询规格信息
        return this.goodsSpecMapper.selectList(
                new LambdaQueryWrapper<GoodsSpec>()
                        .select(GoodsSpec::getId, GoodsSpec::getSpecName)
                        .in(GoodsSpec::getId, specList)
        ).stream().collect(Collectors.toMap(GoodsSpec::getId, GoodsSpec::getSpecName));
    }


    @Override
    public List<OrdersFrontVO> getOrdersByUseId(Long userId) {
        List<OrdersFrontVO> list = this.baseMapper.getOrdersByUseId(userId);
        if (list.isEmpty()) return Collections.emptyList();
        List<List<CartVO>> collect = list.stream().map(OrdersFrontVO::getOrdersItems).collect(Collectors.toList());
        // 查询规格信息
        Map<Long, String> specMap = getSpecList(collect);
        //封装数据
        list.forEach(ordersFrontVO -> {
            //设置商家头像
            if (StrUtil.isNotBlank(ordersFrontVO.getBusinessAvatar())) {
                ordersFrontVO.setBusinessAvatar(ossConfig.getUrl() + ordersFrontVO.getBusinessAvatar());
            }
            // 手机号脱敏
            AddressVO address = ordersFrontVO.getAddress();
            String phone = DesensitizedUtil.mobilePhone(address.getPhone());
            address.setPhone(phone);
            // 处理订单列表数据
            handleCartDataVo(specMap, ordersFrontVO.getOrdersItems());
        });
        return list;
    }

}




